﻿
Imports std

Public Class function_call
    Inherits sentence
    Implements iInvokeableWithOutput

    Public Const parameterStart As Char = character.leftBracket
    Public Const parameterEnd As Char = character.rightBracket

    Protected Friend Shared Shadows Function _isMeaningfulMark(ByVal c As Char) As Boolean
        Return isparameterStart(c) OrElse isparameterEnd(c)
    End Function

    Private functionName As String = Nothing
    Private parameters As parameters_list = Nothing

    Private Sub New(ByVal name As String, ByVal iparameters As parameters_list)
        functionName = name
        parameters = iparameters
    End Sub

    'for value
    Public Overloads Function invoke(ByVal ctx As context, _
                                     ByRef output As bare_variable) As Boolean Implements iInvokeableWithOutput.invoke
        Return invokebase(ctx, output)
    End Function

    Protected Overrides Function invokeImpl(ByVal ctx As context, ByRef output As bare_variable) As Boolean
        assert(Not ctx Is Nothing, "ctx is nothing.")
        Return ctx.invoke(functionName, convertor.cast(Of iParametersBetweenContext)(parameters), output, Me)
    End Function

    'for sentence, do not care about the return value
    Protected Overrides Function invokeImpl(ByVal ctx As context) As Boolean
        Return invokeImpl(ctx, convertor.cast(Of bare_variable)(Nothing))
    End Function

    Private Shared Function isParameterStart(ByVal c As Char) As Boolean
        Return c = parameterStart
    End Function

    Private Shared Function isParameterEnd(ByVal c As Char) As Boolean
        Return c = parameterEnd
    End Function

    Protected Shared Function parseImpl(ByVal input As String, ByRef index As Int64, _
                                        ByRef output As function_call) As Boolean
        Dim name As String = Nothing
        If function_name_defination.parse(input, index, name) AndAlso _
           token(input, index, Nothing, AddressOf isParameterStart, AddressOf [false]) Then
            Dim pl As parameters_list = Nothing
            If parameters_list.parse(input, index, pl) AndAlso _
               token(input, index, Nothing, AddressOf isParameterEnd, AddressOf [false]) Then
                output = New function_call(name, pl)
                Return True
            End If
        End If

        Return False
    End Function

    Public Shared Shadows Function parse(ByVal input As String, ByRef index As Int64, _
                                         ByRef output As function_call) As Boolean
        Return parsebase(input, index, output, AddressOf parseImpl)
    End Function
End Class
